<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Spring Data Redis 是 Spring 框架提供的用于操作 Redis 的方式，最近整理了下它的用法，解决了使用过程中遇到的一些难点与坑点，希望对大家有所帮助。本文涵盖了 Redis 的安装、Spring Cache 结合 Redis 的使用、Redis 连接池的使用和 RedisTemplate 的使用等内容。  #Redis安装 这里提供Linux和Windows两种安装方式，">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Data Redis 最佳实践！">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/42a7eaf90bb7.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="Spring Data Redis 是 Spring 框架提供的用于操作 Redis 的方式，最近整理了下它的用法，解决了使用过程中遇到的一些难点与坑点，希望对大家有所帮助。本文涵盖了 Redis 的安装、Spring Cache 结合 Redis 的使用、Redis 连接池的使用和 RedisTemplate 的使用等内容。  #Redis安装 这里提供Linux和Windows两种安装方式，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:30:05.000Z">
<meta property="article:modified_time" content="2024-02-02T14:50:15.964Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/42a7eaf90bb7.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-02 22:50:15'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Spring Data Redis 最佳实践！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:30:05.000Z" title="发表于 2024-01-21 17:30:05">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-02T14:50:15.964Z" title="更新于 2024-02-02 22:50:15">2024-02-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E5%8F%82%E8%80%83%E7%AF%87/">参考篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring Data Redis 最佳实践！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>Spring Data Redis 是 Spring 框架提供的用于操作 Redis 的方式，最近整理了下它的用法，解决了使用过程中遇到的一些难点与坑点，希望对大家有所帮助。本文涵盖了 Redis 的安装、Spring Cache 结合 Redis 的使用、Redis 连接池的使用和 RedisTemplate 的使用等内容。</p>
</blockquote>
<h2 id="Redis安装"><a href="#Redis安装" class="headerlink" title="#Redis安装"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#redis%E5%AE%89%E8%A3%85">#</a>Redis安装</h2><blockquote>
<p>这里提供Linux和Windows两种安装方式，由于Windows下的版本最高只有3.2版本，所以推荐使用Linux下的版本，目前最新稳定版本为5.0，也是本文中使用的版本。</p>
</blockquote>
<h3 id="Linux"><a href="#Linux" class="headerlink" title="#Linux"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#linux">#</a>Linux</h3><blockquote>
<p>这里我们使用Docker环境下的安装方式。</p>
</blockquote>
<ul>
<li>下载Redis5.0的Docker镜像；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull redis:5.0</span><br></pre></td></tr></table></figure>

<ul>
<li>使用Docker命令启动Redis容器；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">docker run -p 6379:6379 --name redis \</span><br><span class="line">-v /mydata/redis/data:/data \</span><br><span class="line">-d redis:5.0 redis-server --appendonly yes</span><br></pre></td></tr></table></figure>

<h3 id="Windows"><a href="#Windows" class="headerlink" title="#Windows"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#windows">#</a>Windows</h3><blockquote>
<p>想使用Windows版本的朋友可以使用以下安装方式。</p>
</blockquote>
<ul>
<li>下载Windows版本的Redis,下载地址：<a target="_blank" rel="noopener" href="https://github.com/MicrosoftArchive/redis/releases">https://github.com/MicrosoftArchive/redis/releases</a></li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:50:09_spring_boot_redis_01-f3bb1056.png"></p>
<ul>
<li>下载完后解压到指定目录；</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:50:09_spring_boot_redis_02-e96ad8d3.png"></p>
<ul>
<li>在当前地址栏输入cmd后，执行redis的启动命令：redis-server.exe redis.windows.conf</li>
</ul>
<p><img src=""></p>
<ul>
<li>将Redis注册为服务的命令：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 注册服务</span><br><span class="line">redis-server --service-install redis.windows.conf</span><br><span class="line"># 启动服务</span><br><span class="line">redis-server --service-start</span><br><span class="line"># 停止服务</span><br><span class="line">redis-server --service-stop</span><br><span class="line"># 删除服务</span><br><span class="line">redis-server --service-uninstall</span><br></pre></td></tr></table></figure>

<h2 id="Spring-Cache-操作Redis"><a href="#Spring-Cache-操作Redis" class="headerlink" title="#Spring Cache 操作Redis"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#spring-cache-%E6%93%8D%E4%BD%9Credis">#</a>Spring Cache 操作Redis</h2><h3 id="Spring-Cache-简介"><a href="#Spring-Cache-简介" class="headerlink" title="#Spring Cache 简介"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#spring-cache-%E7%AE%80%E4%BB%8B">#</a>Spring Cache 简介</h3><blockquote>
<p>当Spring Boot 结合Redis来作为缓存使用时，最简单的方式就是使用Spring Cache了，使用它我们无需知道Spring中对Redis的各种操作，仅仅通过它提供的@Cacheable 、@CachePut 、@CacheEvict 、@EnableCaching等注解就可以实现缓存功能。</p>
</blockquote>
<h3 id="常用注解"><a href="#常用注解" class="headerlink" title="#常用注解"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3">#</a>常用注解</h3><h4 id="EnableCaching"><a href="#EnableCaching" class="headerlink" title="#@EnableCaching"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#enablecaching">#</a>@EnableCaching</h4><p>开启缓存功能，一般放在启动类上。</p>
<h4 id="Cacheable"><a href="#Cacheable" class="headerlink" title="#@Cacheable"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#cacheable">#</a>@Cacheable</h4><p>使用该注解的方法当缓存存在时，会从缓存中获取数据而不执行方法，当缓存不存在时，会执行方法并把返回结果存入缓存中。<code>一般使用在查询方法上</code>，可以设置如下属性：</p>
<ul>
<li>value：缓存名称（必填），指定缓存的命名空间；</li>
<li>key：用于设置在命名空间中的缓存key值，可以使用SpEL表达式定义；</li>
<li>unless：条件符合则不缓存；</li>
<li>condition：条件符合则缓存。</li>
</ul>
<h4 id="CachePut"><a href="#CachePut" class="headerlink" title="#@CachePut"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#cacheput">#</a>@CachePut</h4><p>使用该注解的方法每次执行时都会把返回结果存入缓存中。<code>一般使用在新增方法上</code>，可以设置如下属性：</p>
<ul>
<li>value：缓存名称（必填），指定缓存的命名空间；</li>
<li>key：用于设置在命名空间中的缓存key值，可以使用SpEL表达式定义；</li>
<li>unless：条件符合则不缓存；</li>
<li>condition：条件符合则缓存。</li>
</ul>
<h4 id="CacheEvict"><a href="#CacheEvict" class="headerlink" title="#@CacheEvict"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#cacheevict">#</a>@CacheEvict</h4><p>使用该注解的方法执行时会清空指定的缓存。<code>一般使用在更新或删除方法上</code>，可以设置如下属性：</p>
<ul>
<li>value：缓存名称（必填），指定缓存的命名空间；</li>
<li>key：用于设置在命名空间中的缓存key值，可以使用SpEL表达式定义；</li>
<li>condition：条件符合则缓存。</li>
</ul>
<h3 id="使用步骤"><a href="#使用步骤" class="headerlink" title="#使用步骤"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4">#</a>使用步骤</h3><ul>
<li>在pom.xml中添加项目依赖：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--redis依赖配置--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>修改配置文件application.yml，添加Redis的连接配置；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  redis:</span><br><span class="line">    host: 192.168.6.139 # Redis服务器地址</span><br><span class="line">    database: 0 # Redis数据库索引（默认为0）</span><br><span class="line">    port: 6379 # Redis服务器连接端口</span><br><span class="line">    password: # Redis服务器连接密码（默认为空）</span><br><span class="line">    timeout: 1000ms # 连接超时时间</span><br></pre></td></tr></table></figure>

<ul>
<li>在启动类上添加@EnableCaching注解启动缓存功能；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@EnableCaching</span><br><span class="line">@SpringBootApplication</span><br><span class="line">public class MallTinyApplication &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        SpringApplication.run(MallTinyApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>接下来在PmsBrandServiceImpl类中使用相关注解来实现缓存功能，可以发现我们获取品牌详情的方法中使用了@Cacheable注解，在修改和删除品牌的方法上使用了@CacheEvict注解；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * PmsBrandService实现类</span><br><span class="line"> * Created by macro on 2019/4/19.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class PmsBrandServiceImpl implements PmsBrandService &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private PmsBrandMapper brandMapper;</span><br><span class="line"></span><br><span class="line">    @CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE, key = &quot;&#x27;pms:brand:&#x27;+#id&quot;)</span><br><span class="line">    @Override</span><br><span class="line">    public int update(Long id, PmsBrand brand) &#123;</span><br><span class="line">        brand.setId(id);</span><br><span class="line">        return brandMapper.updateByPrimaryKeySelective(brand);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE, key = &quot;&#x27;pms:brand:&#x27;+#id&quot;)</span><br><span class="line">    @Override</span><br><span class="line">    public int delete(Long id) &#123;</span><br><span class="line">        return brandMapper.deleteByPrimaryKey(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Cacheable(value = RedisConfig.REDIS_KEY_DATABASE, key = &quot;&#x27;pms:brand:&#x27;+#id&quot;, unless = &quot;#result==null&quot;)</span><br><span class="line">    @Override</span><br><span class="line">    public PmsBrand getItem(Long id) &#123;</span><br><span class="line">        return brandMapper.selectByPrimaryKey(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>我们可以调用获取品牌详情的接口测试下效果，此时发现Redis中存储的数据有点像乱码，并且没有设置过期时间；</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:50:09_spring_boot_redis_04-002a198b.png"></p>
<h2 id="存储JSON格式数据"><a href="#存储JSON格式数据" class="headerlink" title="#存储JSON格式数据"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E5%AD%98%E5%82%A8json%E6%A0%BC%E5%BC%8F%E6%95%B0%E6%8D%AE">#</a>存储JSON格式数据</h2><blockquote>
<p>此时我们就会想到有没有什么办法让Redis中存储的数据变成标准的JSON格式，然后可以设置一定的过期时间，不设置过期时间容易产生很多不必要的缓存数据。</p>
</blockquote>
<ul>
<li>我们可以通过给RedisTemplate设置JSON格式的序列化器，并通过配置RedisCacheConfiguration设置超时时间来实现以上需求，此时别忘了去除启动类上的@EnableCaching注解，具体配置类RedisConfig代码如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Redis配置类</span><br><span class="line"> * Created by macro on 2020/3/2.</span><br><span class="line"> */</span><br><span class="line">@EnableCaching</span><br><span class="line">@Configuration</span><br><span class="line">public class RedisConfig extends CachingConfigurerSupport &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * redis数据库自定义key</span><br><span class="line">     */</span><br><span class="line">    public  static final String REDIS_KEY_DATABASE=&quot;mall&quot;;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) &#123;</span><br><span class="line">        RedisSerializer&lt;Object&gt; serializer = redisSerializer();</span><br><span class="line">        RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;&gt;();</span><br><span class="line">        redisTemplate.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        redisTemplate.setKeySerializer(new StringRedisSerializer());</span><br><span class="line">        redisTemplate.setValueSerializer(serializer);</span><br><span class="line">        redisTemplate.setHashKeySerializer(new StringRedisSerializer());</span><br><span class="line">        redisTemplate.setHashValueSerializer(serializer);</span><br><span class="line">        redisTemplate.afterPropertiesSet();</span><br><span class="line">        return redisTemplate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public RedisSerializer&lt;Object&gt; redisSerializer() &#123;</span><br><span class="line">        //创建JSON序列化器</span><br><span class="line">        Jackson2JsonRedisSerializer&lt;Object&gt; serializer = new Jackson2JsonRedisSerializer&lt;&gt;(Object.class);</span><br><span class="line">        ObjectMapper objectMapper = new ObjectMapper();</span><br><span class="line">        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);</span><br><span class="line">        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);</span><br><span class="line">        serializer.setObjectMapper(objectMapper);</span><br><span class="line">        return serializer;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) &#123;</span><br><span class="line">        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);</span><br><span class="line">        //设置Redis缓存有效期为1天</span><br><span class="line">        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()</span><br><span class="line">                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));</span><br><span class="line">        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>此时我们再次调用获取商品详情的接口进行测试，会发现Redis中已经缓存了标准的JSON格式数据，并且超时时间被设置为了1天。</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_22:50:09_spring_boot_redis_05-3ec55dfc.png"></p>
<h2 id="使用Redis连接池"><a href="#使用Redis连接池" class="headerlink" title="#使用Redis连接池"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E4%BD%BF%E7%94%A8redis%E8%BF%9E%E6%8E%A5%E6%B1%A0">#</a>使用Redis连接池</h2><blockquote>
<p>SpringBoot 1.5.x版本Redis客户端默认是Jedis实现的，SpringBoot 2.x版本中默认客户端是用Lettuce实现的，我们先来了解下Jedis和Lettuce客户端。</p>
</blockquote>
<h3 id="Jedis-vs-Lettuce"><a href="#Jedis-vs-Lettuce" class="headerlink" title="#Jedis vs Lettuce"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#jedis-vs-lettuce">#</a>Jedis vs Lettuce</h3><p>Jedis在实现上是直连Redis服务，多线程环境下非线程安全，除非使用连接池，为每个 RedisConnection 实例增加物理连接。</p>
<p>Lettuce是一种可伸缩，线程安全，完全非阻塞的Redis客户端，多个线程可以共享一个RedisConnection，它利用Netty NIO框架来高效地管理多个连接，从而提供了异步和同步数据访问方式，用于构建非阻塞的反应性应用程序。</p>
<h3 id="使用步骤-1"><a href="#使用步骤-1" class="headerlink" title="#使用步骤"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4-1">#</a>使用步骤</h3><ul>
<li>修改application.yml添加Lettuce连接池配置，用于配置线程数量和阻塞等待时间；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  redis:</span><br><span class="line">    lettuce:</span><br><span class="line">      pool:</span><br><span class="line">        max-active: 8 # 连接池最大连接数</span><br><span class="line">        max-idle: 8 # 连接池最大空闲连接数</span><br><span class="line">        min-idle: 0 # 连接池最小空闲连接数</span><br><span class="line">        max-wait: -1ms # 连接池最大阻塞等待时间，负值表示没有限制</span><br></pre></td></tr></table></figure>

<ul>
<li>由于SpringBoot 2.x中默认并没有使用Redis连接池，所以需要在pom.xml中添加commons-pool2的依赖；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;commons-pool2&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果你没添加以上依赖的话，启动应用的时候就会产生如下错误；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig</span><br><span class="line">	at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration$LettucePoolingClientConfigurationBuilder.&lt;init&gt;(LettucePoolingClientConfiguration.java:84) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]</span><br><span class="line">	at org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration.builder(LettucePoolingClientConfiguration.java:48) ~[spring-data-redis-2.1.5.RELEASE.jar:2.1.5.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$PoolBuilderFactory.createBuilder(LettuceConnectionConfiguration.java:149) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.createBuilder(LettuceConnectionConfiguration.java:107) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.getLettuceClientConfiguration(LettuceConnectionConfiguration.java:93) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.redisConnectionFactory(LettuceConnectionConfiguration.java:74) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47.CGLIB$redisConnectionFactory$0(&lt;generated&gt;) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47$$FastClassBySpringCGLIB$$b8ae2813.invoke(&lt;generated&gt;) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]</span><br><span class="line">	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]</span><br><span class="line">	at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$5caa7e47.redisConnectionFactory(&lt;generated&gt;) ~[spring-boot-autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]</span><br><span class="line">	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]</span><br><span class="line">	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]</span><br><span class="line">	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]</span><br><span class="line">	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]</span><br><span class="line">	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]</span><br><span class="line">	... 111 common frames omitted</span><br></pre></td></tr></table></figure>

<h2 id="自由操作Redis"><a href="#自由操作Redis" class="headerlink" title="#自由操作Redis"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E8%87%AA%E7%94%B1%E6%93%8D%E4%BD%9Credis">#</a>自由操作Redis</h2><blockquote>
<p>Spring Cache 给我们提供了操作Redis缓存的便捷方法，但是也有很多局限性。比如说我们想单独设置一个缓存值的有效期怎么办？我们并不想缓存方法的返回值，我们想缓存方法中产生的中间值怎么办？此时我们就需要用到RedisTemplate这个类了，接下来我们来讲下如何通过RedisTemplate来自由操作Redis中的缓存。</p>
</blockquote>
<h3 id="RedisService"><a href="#RedisService" class="headerlink" title="#RedisService"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#redisservice">#</a>RedisService</h3><blockquote>
<p>定义Redis操作业务类，在Redis中有几种数据结构，比如普通结构（对象），Hash结构、Set结构、List结构，该接口中定义了大多数常用操作方法。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * redis操作Service</span><br><span class="line"> * Created by macro on 2020/3/3.</span><br><span class="line"> */</span><br><span class="line">public interface RedisService &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 保存属性</span><br><span class="line">     */</span><br><span class="line">    void set(String key, Object value, long time);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 保存属性</span><br><span class="line">     */</span><br><span class="line">    void set(String key, Object value);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取属性</span><br><span class="line">     */</span><br><span class="line">    Object get(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 删除属性</span><br><span class="line">     */</span><br><span class="line">    Boolean del(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 批量删除属性</span><br><span class="line">     */</span><br><span class="line">    Long del(List&lt;String&gt; keys);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 设置过期时间</span><br><span class="line">     */</span><br><span class="line">    Boolean expire(String key, long time);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取过期时间</span><br><span class="line">     */</span><br><span class="line">    Long getExpire(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断是否有该属性</span><br><span class="line">     */</span><br><span class="line">    Boolean hasKey(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 按delta递增</span><br><span class="line">     */</span><br><span class="line">    Long incr(String key, long delta);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 按delta递减</span><br><span class="line">     */</span><br><span class="line">    Long decr(String key, long delta);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取Hash结构中的属性</span><br><span class="line">     */</span><br><span class="line">    Object hGet(String key, String hashKey);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向Hash结构中放入一个属性</span><br><span class="line">     */</span><br><span class="line">    Boolean hSet(String key, String hashKey, Object value, long time);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向Hash结构中放入一个属性</span><br><span class="line">     */</span><br><span class="line">    void hSet(String key, String hashKey, Object value);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 直接获取整个Hash结构</span><br><span class="line">     */</span><br><span class="line">    Map&lt;Object, Object&gt; hGetAll(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 直接设置整个Hash结构</span><br><span class="line">     */</span><br><span class="line">    Boolean hSetAll(String key, Map&lt;String, Object&gt; map, long time);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 直接设置整个Hash结构</span><br><span class="line">     */</span><br><span class="line">    void hSetAll(String key, Map&lt;String, Object&gt; map);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 删除Hash结构中的属性</span><br><span class="line">     */</span><br><span class="line">    void hDel(String key, Object... hashKey);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断Hash结构中是否有该属性</span><br><span class="line">     */</span><br><span class="line">    Boolean hHasKey(String key, String hashKey);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Hash结构中属性递增</span><br><span class="line">     */</span><br><span class="line">    Long hIncr(String key, String hashKey, Long delta);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Hash结构中属性递减</span><br><span class="line">     */</span><br><span class="line">    Long hDecr(String key, String hashKey, Long delta);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取Set结构</span><br><span class="line">     */</span><br><span class="line">    Set&lt;Object&gt; sMembers(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向Set结构中添加属性</span><br><span class="line">     */</span><br><span class="line">    Long sAdd(String key, Object... values);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向Set结构中添加属性</span><br><span class="line">     */</span><br><span class="line">    Long sAdd(String key, long time, Object... values);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 是否为Set中的属性</span><br><span class="line">     */</span><br><span class="line">    Boolean sIsMember(String key, Object value);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取Set结构的长度</span><br><span class="line">     */</span><br><span class="line">    Long sSize(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 删除Set结构中的属性</span><br><span class="line">     */</span><br><span class="line">    Long sRemove(String key, Object... values);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取List结构中的属性</span><br><span class="line">     */</span><br><span class="line">    List&lt;Object&gt; lRange(String key, long start, long end);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取List结构的长度</span><br><span class="line">     */</span><br><span class="line">    Long lSize(String key);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据索引获取List中的属性</span><br><span class="line">     */</span><br><span class="line">    Object lIndex(String key, long index);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向List结构中添加属性</span><br><span class="line">     */</span><br><span class="line">    Long lPush(String key, Object value);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向List结构中添加属性</span><br><span class="line">     */</span><br><span class="line">    Long lPush(String key, Object value, long time);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向List结构中批量添加属性</span><br><span class="line">     */</span><br><span class="line">    Long lPushAll(String key, Object... values);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 向List结构中批量添加属性</span><br><span class="line">     */</span><br><span class="line">    Long lPushAll(String key, Long time, Object... values);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从List结构中移除属性</span><br><span class="line">     */</span><br><span class="line">    Long lRemove(String key, long count, Object value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="RedisServiceImpl"><a href="#RedisServiceImpl" class="headerlink" title="#RedisServiceImpl"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#redisserviceimpl">#</a>RedisServiceImpl</h3><blockquote>
<p>RedisService的实现类，使用RedisTemplate来自由操作Redis中的缓存数据。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * redis操作实现类</span><br><span class="line"> * Created by macro on 2020/3/3.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class RedisServiceImpl implements RedisService &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private RedisTemplate&lt;String, Object&gt; redisTemplate;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void set(String key, Object value, long time) &#123;</span><br><span class="line">        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void set(String key, Object value) &#123;</span><br><span class="line">        redisTemplate.opsForValue().set(key, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Object get(String key) &#123;</span><br><span class="line">        return redisTemplate.opsForValue().get(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean del(String key) &#123;</span><br><span class="line">        return redisTemplate.delete(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long del(List&lt;String&gt; keys) &#123;</span><br><span class="line">        return redisTemplate.delete(keys);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean expire(String key, long time) &#123;</span><br><span class="line">        return redisTemplate.expire(key, time, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long getExpire(String key) &#123;</span><br><span class="line">        return redisTemplate.getExpire(key, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean hasKey(String key) &#123;</span><br><span class="line">        return redisTemplate.hasKey(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long incr(String key, long delta) &#123;</span><br><span class="line">        return redisTemplate.opsForValue().increment(key, delta);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long decr(String key, long delta) &#123;</span><br><span class="line">        return redisTemplate.opsForValue().increment(key, -delta);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Object hGet(String key, String hashKey) &#123;</span><br><span class="line">        return redisTemplate.opsForHash().get(key, hashKey);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean hSet(String key, String hashKey, Object value, long time) &#123;</span><br><span class="line">        redisTemplate.opsForHash().put(key, hashKey, value);</span><br><span class="line">        return expire(key, time);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void hSet(String key, String hashKey, Object value) &#123;</span><br><span class="line">        redisTemplate.opsForHash().put(key, hashKey, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Map&lt;Object, Object&gt; hGetAll(String key) &#123;</span><br><span class="line">        return redisTemplate.opsForHash().entries(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean hSetAll(String key, Map&lt;String, Object&gt; map, long time) &#123;</span><br><span class="line">        redisTemplate.opsForHash().putAll(key, map);</span><br><span class="line">        return expire(key, time);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void hSetAll(String key, Map&lt;String, Object&gt; map) &#123;</span><br><span class="line">        redisTemplate.opsForHash().putAll(key, map);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void hDel(String key, Object... hashKey) &#123;</span><br><span class="line">        redisTemplate.opsForHash().delete(key, hashKey);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean hHasKey(String key, String hashKey) &#123;</span><br><span class="line">        return redisTemplate.opsForHash().hasKey(key, hashKey);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long hIncr(String key, String hashKey, Long delta) &#123;</span><br><span class="line">        return redisTemplate.opsForHash().increment(key, hashKey, delta);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long hDecr(String key, String hashKey, Long delta) &#123;</span><br><span class="line">        return redisTemplate.opsForHash().increment(key, hashKey, -delta);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Set&lt;Object&gt; sMembers(String key) &#123;</span><br><span class="line">        return redisTemplate.opsForSet().members(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long sAdd(String key, Object... values) &#123;</span><br><span class="line">        return redisTemplate.opsForSet().add(key, values);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long sAdd(String key, long time, Object... values) &#123;</span><br><span class="line">        Long count = redisTemplate.opsForSet().add(key, values);</span><br><span class="line">        expire(key, time);</span><br><span class="line">        return count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Boolean sIsMember(String key, Object value) &#123;</span><br><span class="line">        return redisTemplate.opsForSet().isMember(key, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long sSize(String key) &#123;</span><br><span class="line">        return redisTemplate.opsForSet().size(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long sRemove(String key, Object... values) &#123;</span><br><span class="line">        return redisTemplate.opsForSet().remove(key, values);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public List&lt;Object&gt; lRange(String key, long start, long end) &#123;</span><br><span class="line">        return redisTemplate.opsForList().range(key, start, end);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lSize(String key) &#123;</span><br><span class="line">        return redisTemplate.opsForList().size(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Object lIndex(String key, long index) &#123;</span><br><span class="line">        return redisTemplate.opsForList().index(key, index);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lPush(String key, Object value) &#123;</span><br><span class="line">        return redisTemplate.opsForList().rightPush(key, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lPush(String key, Object value, long time) &#123;</span><br><span class="line">        Long index = redisTemplate.opsForList().rightPush(key, value);</span><br><span class="line">        expire(key, time);</span><br><span class="line">        return index;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lPushAll(String key, Object... values) &#123;</span><br><span class="line">        return redisTemplate.opsForList().rightPushAll(key, values);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lPushAll(String key, Long time, Object... values) &#123;</span><br><span class="line">        Long count = redisTemplate.opsForList().rightPushAll(key, values);</span><br><span class="line">        expire(key, time);</span><br><span class="line">        return count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Long lRemove(String key, long count, Object value) &#123;</span><br><span class="line">        return redisTemplate.opsForList().remove(key, count, value);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="RedisController"><a href="#RedisController" class="headerlink" title="#RedisController"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#rediscontroller">#</a>RedisController</h3><blockquote>
<p>测试RedisService中缓存操作的Controller，大家可以调用测试下。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Redis测试Controller</span><br><span class="line"> * Created by macro on 2020/3/3.</span><br><span class="line"> */</span><br><span class="line">@Api(tags = &quot;RedisController&quot;, description = &quot;Redis测试&quot;)</span><br><span class="line">@Controller</span><br><span class="line">@RequestMapping(&quot;/redis&quot;)</span><br><span class="line">public class RedisController &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private RedisService redisService;</span><br><span class="line">    @Autowired</span><br><span class="line">    private PmsBrandService brandService;</span><br><span class="line"></span><br><span class="line">    @ApiOperation(&quot;测试简单缓存&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/simpleTest&quot;, method = RequestMethod.GET)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult&lt;PmsBrand&gt; simpleTest() &#123;</span><br><span class="line">        List&lt;PmsBrand&gt; brandList = brandService.list(1, 5);</span><br><span class="line">        PmsBrand brand = brandList.get(0);</span><br><span class="line">        String key = &quot;redis:simple:&quot; + brand.getId();</span><br><span class="line">        redisService.set(key, brand);</span><br><span class="line">        PmsBrand cacheBrand = (PmsBrand) redisService.get(key);</span><br><span class="line">        return CommonResult.success(cacheBrand);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ApiOperation(&quot;测试Hash结构的缓存&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/hashTest&quot;, method = RequestMethod.GET)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult&lt;PmsBrand&gt; hashTest() &#123;</span><br><span class="line">        List&lt;PmsBrand&gt; brandList = brandService.list(1, 5);</span><br><span class="line">        PmsBrand brand = brandList.get(0);</span><br><span class="line">        String key = &quot;redis:hash:&quot; + brand.getId();</span><br><span class="line">        Map&lt;String, Object&gt; value = BeanUtil.beanToMap(brand);</span><br><span class="line">        redisService.hSetAll(key, value);</span><br><span class="line">        Map&lt;Object, Object&gt; cacheValue = redisService.hGetAll(key);</span><br><span class="line">        PmsBrand cacheBrand = BeanUtil.mapToBean(cacheValue, PmsBrand.class, true);</span><br><span class="line">        return CommonResult.success(cacheBrand);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ApiOperation(&quot;测试Set结构的缓存&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/setTest&quot;, method = RequestMethod.GET)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult&lt;Set&lt;Object&gt;&gt; setTest() &#123;</span><br><span class="line">        List&lt;PmsBrand&gt; brandList = brandService.list(1, 5);</span><br><span class="line">        String key = &quot;redis:set:all&quot;;</span><br><span class="line">        redisService.sAdd(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));</span><br><span class="line">        redisService.sRemove(key, brandList.get(0));</span><br><span class="line">        Set&lt;Object&gt; cachedBrandList = redisService.sMembers(key);</span><br><span class="line">        return CommonResult.success(cachedBrandList);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @ApiOperation(&quot;测试List结构的缓存&quot;)</span><br><span class="line">    @RequestMapping(value = &quot;/listTest&quot;, method = RequestMethod.GET)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public CommonResult&lt;List&lt;Object&gt;&gt; listTest() &#123;</span><br><span class="line">        List&lt;PmsBrand&gt; brandList = brandService.list(1, 5);</span><br><span class="line">        String key = &quot;redis:list:all&quot;;</span><br><span class="line">        redisService.lPushAll(key, (Object[]) ArrayUtil.toArray(brandList, PmsBrand.class));</span><br><span class="line">        redisService.lRemove(key, 1, brandList.get(0));</span><br><span class="line">        List&lt;Object&gt; cachedBrandList = redisService.lRange(key, 0, 3);</span><br><span class="line">        return CommonResult.success(cachedBrandList);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/spring_data_redis.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-redis">https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-redis</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/42a7eaf90bb7.html">https://ko25891wan.gitlab.io/2024/01/42a7eaf90bb7.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/27851c2fc81c.html" title="SpringBoot应用整合ELK实现日志收集"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">SpringBoot应用整合ELK实现日志收集</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/75e60928f39d.html" title="Nginx如何支持HTTPS？手把手教贼简单！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Nginx如何支持HTTPS？手把手教贼简单！</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Redis%E5%AE%89%E8%A3%85"><span class="toc-number">1.</span> <span class="toc-text">Redis安装</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Linux"><span class="toc-number">1.1.</span> <span class="toc-text">Linux</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Windows"><span class="toc-number">1.2.</span> <span class="toc-text">Windows</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-Cache-%E6%93%8D%E4%BD%9CRedis"><span class="toc-number">2.</span> <span class="toc-text">Spring Cache 操作Redis</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Spring-Cache-%E7%AE%80%E4%BB%8B"><span class="toc-number">2.1.</span> <span class="toc-text">Spring Cache 简介</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.2.</span> <span class="toc-text">常用注解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#EnableCaching"><span class="toc-number">2.2.1.</span> <span class="toc-text">@EnableCaching</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Cacheable"><span class="toc-number">2.2.2.</span> <span class="toc-text">@Cacheable</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CachePut"><span class="toc-number">2.2.3.</span> <span class="toc-text">@CachePut</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CacheEvict"><span class="toc-number">2.2.4.</span> <span class="toc-text">@CacheEvict</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4"><span class="toc-number">2.3.</span> <span class="toc-text">使用步骤</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AD%98%E5%82%A8JSON%E6%A0%BC%E5%BC%8F%E6%95%B0%E6%8D%AE"><span class="toc-number">3.</span> <span class="toc-text">存储JSON格式数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Redis%E8%BF%9E%E6%8E%A5%E6%B1%A0"><span class="toc-number">4.</span> <span class="toc-text">使用Redis连接池</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Jedis-vs-Lettuce"><span class="toc-number">4.1.</span> <span class="toc-text">Jedis vs Lettuce</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%AD%A5%E9%AA%A4-1"><span class="toc-number">4.2.</span> <span class="toc-text">使用步骤</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E7%94%B1%E6%93%8D%E4%BD%9CRedis"><span class="toc-number">5.</span> <span class="toc-text">自由操作Redis</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#RedisService"><span class="toc-number">5.1.</span> <span class="toc-text">RedisService</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RedisServiceImpl"><span class="toc-number">5.2.</span> <span class="toc-text">RedisServiceImpl</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RedisController"><span class="toc-number">5.3.</span> <span class="toc-text">RedisController</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">6.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>